package com.free.wx.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.free.common.core.web.domain.R;
import com.free.qq.weixin.mp.aes.AesException;
import com.free.wx.pojo.ReceiveMessageReq;
import com.free.wx.pojo.WxLoginReq;
import com.free.wx.properties.WxProperties;
import com.free.system.api.RemoteAuthService;
import com.free.system.api.RemoteNoteService;
import com.free.system.api.domain.LoginBody;
import com.free.system.api.domain.ZoneNote;
import com.free.wx.pojo.VerifyTokenReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
public class WxController {

    @Autowired
    WxProperties wxProperties;
    @Autowired
    RemoteNoteService remoteNoteService;
    @Autowired
    RemoteAuthService remoteAuthService;

    /**
     * 验证token
     *
     * @return
     */
    @GetMapping("verifyToken" )
    public String verifyToken(VerifyTokenReq tokenReq) throws AesException {
        log.info("获取到的请求：{}" , tokenReq);
        log.info("获取到的token：{}" , wxProperties.getToken());
        //排序并拼接
        List<String> list = Arrays.asList(wxProperties.getToken(), tokenReq.getTimestamp(), tokenReq.getNonce());
        Collections.sort(list);
        String join = String.join("" , list);
        String sha1 = DigestUtil.sha1Hex(join);
        if (sha1.equalsIgnoreCase(tokenReq.getSignature())) {
            return tokenReq.getEchostr();
        }
        return "fail";
    }

    /**
     * 微信登录
     *
     * @return
     */
    @PostMapping("wxParseLoginCode" )
    public R wxParseLoginCode(@RequestBody WxLoginReq wxLoginReq) throws AesException {
        log.info("获取到的请求：{}" , wxLoginReq);
        wxProperties.getToken();
        String apiJscode2session = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=%s";
        String apiJscode2sessionRes = HttpUtil.get(String.format(apiJscode2session, wxProperties.getAppid(), wxProperties.getSecret(), wxLoginReq.getCode(), wxProperties.getGrantType()));
        JSONObject apiJscode2sessionResParse = JSONUtil.parseObj(apiJscode2sessionRes);
        if (ObjectUtil.isNotEmpty(apiJscode2sessionResParse.getStr("errmsg" ))) {
            return R.fail(apiJscode2sessionResParse.getStr("errmsg" ));
        }
        LoginBody loginBody = new LoginBody();
        loginBody.setLoginType("wx" );
        loginBody.setWxOpenId(apiJscode2sessionResParse.getStr("openid" ));
        System.out.println(apiJscode2sessionRes);
        return R.ok(remoteAuthService.login(loginBody).getData());
    }

    /**
     * 接收消息并回复
     *
     * @param messageReq
     * @return
     * @throws AesException
     */
    @PostMapping(path = "verifyToken" , produces = {"application/xml"})
    public String verifyToken(@RequestBody ReceiveMessageReq messageReq) throws AesException {
        log.info("进来了----{}" , messageReq);
        String resXml = "";
        ZoneNote zoneNote = new ZoneNote();
        zoneNote.setClassify(100);
        R<ZoneNote> noteRes = null;

        if ("text".equals(messageReq.getMsgType())) {
            String title = "翻箱倒柜也没找到~~";
            if ("摘抄".equals(messageReq.getContent())) {
                noteRes = remoteNoteService.getRandomOneByClassify("100" );
                if (ObjectUtil.isNotEmpty(noteRes) && ObjectUtil.isNotEmpty(noteRes.getData())) {
                    title = noteRes.getData().getTitle();
                }
                resXml = "<xml>\n" +
                        "  <ToUserName><![CDATA[" + messageReq.getFromUserName() + "]]></ToUserName>\n" +
                        "  <FromUserName><![CDATA[" + messageReq.getToUserName() + "]]></FromUserName>\n" +
                        "  <CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
                        "  <MsgType><![CDATA[text]]></MsgType>\n" +
                        "  <Content><![CDATA[" + title + "]]></Content>\n" +
                        "</xml>";
            }
            //图片
            if ("图片".equals(messageReq.getContent())) {
                noteRes = remoteNoteService.getRandomOneByClassify("110" );
                if (ObjectUtil.isNotEmpty(noteRes) && ObjectUtil.isNotEmpty(noteRes.getData())) {
                    title = noteRes.getData().getTitle();
                }
                resXml = "<xml>\n" +
                        "  <ToUserName><![CDATA[" + messageReq.getFromUserName() + "]]></ToUserName>\n" +
                        "  <FromUserName><![CDATA[" + messageReq.getToUserName() + "]]></FromUserName>\n" +
                        "  <CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
                        "  <MsgType><![CDATA[image]]></MsgType>\n" +
                        "  <Content><![CDATA[" + title + "]]></Content>\n" +
                        "</xml>";
            }

        } else {
            resXml = "<xml>\n" +
                    "  <ToUserName><![CDATA[" + messageReq.getFromUserName() + "]]></ToUserName>\n" +
                    "  <FromUserName><![CDATA[" + messageReq.getToUserName() + "]]></FromUserName>\n" +
                    "  <CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
                    "  <MsgType><![CDATA[text]]></MsgType>\n" +
                    "  <Content><![CDATA[你说啥，这儿信号不好]]></Content>\n" +
                    "</xml>";
        }
        log.info("返回的消息：" + resXml);
        return resXml;
    }
}
